package com.songcan.common.vo;


import com.songcan.common.contans.CoreContants;
import com.songcan.common.exception.ObjectNotException;
import com.songcan.common.exception.ParamNotException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.LinkedHashMap;

import static com.songcan.common.contans.CoreContants.*;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Slf4j
public class CoreResult {

    private String code;
    private String msg;
    private Object data;


    /**
     * 自定义成功返回提示信息
     * @param message
     */
    public CoreResult(String message){
        this.code = SUCCESS;
        this.msg = message;
    }

    public CoreResult(String code,String message){
        this.code = code;
        this.msg = message;
    }

    public CoreResult(LinkedHashMap jsonObject){
         String status = jsonObject.get("status").toString();
         switch (status){
             case "404":{
                 this.code = NOT_SERVICE;
                 this.msg = jsonObject.get("message").toString();
             }
             break;
             default:{
                 this.code = UNKNOWN;
                 this.msg = jsonObject.get("message").toString();
             }
             break;
         }
    }

    public CoreResult(Object result){
            this.code = SUCCESS;
            this.msg = "success";
            this.data = result;
    }



    public void setException(Exception exception) {
        this.code = CoreResult(exception);
        this.msg = exception.getMessage();
    }

    private static String CoreResult(Throwable throwable){
        if(throwable instanceof ObjectNotException) {
            return CoreContants.ERROR_ENTITY_NOT_EXISTS;
        }
        if(throwable instanceof ParamNotException){
            return ERROR_PARAM_ILLEGAL;
        }

        return  UNKNOWN;
    }
}
